<template>
  <view class="join-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <text class="back-icon">←</text>
        <text class="back-text">返回</text>
      </view>
      <text class="header-title">申请加入家谱</text>
      <view class="header-right"></view>
    </view>

    <!-- 申请表单 -->
    <view class="form-container">
      <view class="form-section">
        <view class="section-title">基本信息</view>

        <!-- 申请说明，只在未弹窗时显示 -->
        <view v-if="!showMemberPopup" class="form-item">
          <text class="label required">申请说明</text>
          <textarea
            v-model="joinReasonForm.reason"
            class="textarea"
            placeholder="请简要说明申请加入的原因，如：我是该家族的后裔，希望加入家谱记录"
            maxlength="100"
            :rows="3"
            @input="onReasonInput"
          />
          <text class="char-count" :class="{ warning: joinReasonForm.reason.length >= 90 }">
            {{ joinReasonForm.reason.length }}/100
          </text>
        </view>
      </view>

      <!-- 家谱树可视化编辑部分，只在未弹窗时显示 -->
      <view v-if="!showMemberPopup" class="form-section">
        <view class="section-title">
          <text>家谱关系图</text>
          <text class="section-subtitle">请添加家庭成员信息</text>
        </view>

        <!-- 家谱树容器 -->
        <view class="family-tree-container">
          <!-- <view class="tree-header">
            <text class="tree-title">家庭成员关系图</text>
            <button class="btn btn-sm btn-primary" @click="addFamilyMember">
              <text class="btn-icon">+</text>
              <text>添加成员</text>
            </button>
          </view> -->

          <view class="tree-content">
            <view v-if="!familyTree || familyTree.length === 0" class="empty-state">
              <text class="empty-icon">👥</text>
              <text class="empty-text">暂无家庭成员信息</text>
              <text class="empty-tip">请点击上方按钮添加家庭成员</text>
            </view>

            <!-- 使用新的树型显示组件 -->
            <scroll-view v-else :scroll-x="true" :scroll-y="true" class="tree-scroll-container">
              <view class="tree-canvas" :style="{ transform: `scale(${treeScale})` }">
                <GenealogyGeneration
                  v-for="(member, index) in familyTree"
                  :key="member.id"
                  :person="member"
                  :generation="1"
                  :level="0"
                  :index="index"
                  :parent-x="getMemberX(member, index)"
                  :parent-y="getMemberY(member)"
                  :family-members="familyMembers"
                  :isFu="true"
                  @node-click="handleNodeClick"
                  @action="handleTreeAction"
                />
              </view>
            </scroll-view>

            <!-- 缩放控制 -->
            <view v-if="familyTree && familyTree.length > 0" class="zoom-controls">
              <button class="zoom-btn" @click="zoomIn">+</button>
              <button class="zoom-btn" @click="zoomOut">-</button>
              <button class="zoom-btn" @click="resetZoom">重置</button>
            </view>
          </view>
        </view>

        <view class="form-tip">
          <text class="tip-icon">💡</text>
          <text class="tip-text">
            请在家谱树中添加父辈、本人等重要家庭成员信息，至少需要包含本人信息
          </text>
        </view>

        <view class="tree-tips">
          <text class="tip-title">操作说明：</text>
          <text class="tip-item">• 点击成员卡片可编辑信息</text>
          <text class="tip-item">• 点击 ⋮ 按钮可添加父辈、子辈或配偶</text>
          <text class="tip-item">• 使用缩放按钮调整视图大小</text>
          <text class="tip-item">• 拖拽滚动查看完整家谱树</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="btn btn-default" :disabled="isSubmitting" @click="goBack">取消</button>
      <button
        class="btn btn-primary"
        :disabled="!canSubmit || isSubmitting"
        @click="submitApplication"
      >
        <text v-if="isSubmitting">提交中...</text>
        <text v-else>提交申请</text>
      </button>
    </view>
    <!-- 操作选项弹出框 -->
    <view v-if="optListFlag" class="opt-popup-overlay" @click="optListFlag = false">
      <!-- 下面是弹窗内所有 handleTreeAction 的替换 -->
      <view class="opt-popup-container" @click.stop>
        <view class="opt-popup-header">
          <text class="opt-popup-title">成员操作</text>
          <text class="opt-popup-close" @click="optListFlag = false">×</text>
        </view>
        <view class="opt-popup-actions">
          <!-- 编辑操作 - 始终显示 -->
          <view
            class="opt-action-item"
            @click="
              handleTreeAction({ action: 'edit', person: editingMember });
              optListFlag = false;
            "
          >
            <text class="action-icon">✏️</text>
            <text class="action-text">编辑信息</text>
          </view>

          <!-- 当只有一个节点且有数据时，显示添加父辈和子辈操作 -->
          <template v-if="familyMembers.length === 1 && hasNodeData(editingMember)">
            <!-- 添加父辈操作 -->
            <view
              class="opt-action-item"
              @click="
                handleTreeAction({ action: 'add-parent', person: editingMember });
                optListFlag = false;
              "
            >
              <text class="action-icon">👴</text>
              <text class="action-text">添加父辈</text>
            </view>

            <!-- 添加子辈操作 -->
            <view
              class="opt-action-item"
              @click="
                handleTreeAction({ action: 'add-child', person: editingMember });
                optListFlag = false;
              "
            >
              <text class="action-icon">👶</text>
              <text class="action-text">添加子辈</text>
            </view>
          </template>

          <!-- 当有多个节点时，显示所有操作 -->
          <template v-if="familyMembers.length > 1">
            <!-- 添加父辈操作 - 只有没有父辈的成员才显示 -->
            <view
              v-if="!editingMember.parentId"
              class="opt-action-item"
              @click="
                handleTreeAction({ action: 'add-parent', person: editingMember });
                optListFlag = false;
              "
            >
              <text class="action-icon">👴</text>
              <text class="action-text">添加父辈</text>
            </view>

            <!-- 添加子辈操作 -->
            <view
              class="opt-action-item"
              @click="
                handleTreeAction({ action: 'add-child', person: editingMember });
                optListFlag = false;
              "
            >
              <text class="action-icon">👶</text>
              <text class="action-text">添加子辈</text>
            </view>

            <!-- 添加配偶操作 -->
            <view
              class="opt-action-item"
              @click="
                handleTreeAction({ action: 'add-spouse', person: editingMember });
                optListFlag = false;
              "
            >
              <text class="action-icon">💕</text>
              <text class="action-text">添加配偶</text>
            </view>

            <!-- 删除操作 - 只有非本人且没有子辈的成员才显示，或者配偶可以删除 -->
            <view
              v-if="
                (!editingMember.isSelf && !hasChildren(editingMember)) || isSpouse(editingMember)
              "
              class="opt-action-item delete"
              @click="
                handleTreeAction({ action: 'delete', person: editingMember });
                optListFlag = false;
              "
            >
              <text class="action-icon">🗑️</text>
              <text class="action-text">删除{{ isSpouse(editingMember) ? "配偶" : "成员" }}</text>
            </view>
          </template>
        </view>
      </view>
    </view>
    <!-- 成员编辑弹窗 -->
    <view v-if="showMemberPopup" class="popup-overlay">
      <view class="popup-container" @click.stop>
        <view class="popup-header">
          <text class="popup-title">
            {{
              editingFlag === 0
                ? "编辑成员"
                : editingFlag === 1
                  ? "添加父辈"
                  : editingFlag === 2
                    ? "添加子辈"
                    : editingFlag === 3
                      ? "添加配偶"
                      : editingFlag
                        ? "编辑成员"
                        : "添加成员"
            }}
          </text>
          <text class="popup-close" @click="closeMemberPopup">×</text>
        </view>

        <view class="popup-content">
          <view class="form-item">
            <text class="label required">姓氏</text>
            <input
              v-model="memberForm.firstName"
              class="input"
              type="text"
              placeholder="请输入姓氏"
              maxlength="10"
              @input="onFirstNameInput"
            />
          </view>

          <view class="form-item">
            <text class="label required">名字</text>
            <input
              v-model="memberForm.lastName"
              class="input"
              type="text"
              placeholder="请输入名字"
              maxlength="20"
              @input="onLastNameInput"
            />
          </view>

          <!-- 新增：选择父节点 -->
          <!--          <view class="form-item">
            <text class="label">父节点</text>
            <picker :value="parentIndex" :range="parentOptions" @change="onParentChange">
              <view class="picker-input">
                <text>{{ parentOptions[parentIndex] }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view> -->

          <view class="form-item">
            <text class="label required">性别</text>
            <view class="radio-group">
              <view
                class="radio-item"
                :class="{ active: memberForm.gender === 1 }"
                @click="memberForm.gender = 1"
              >
                <text class="radio-icon">👨</text>
                <text>男</text>
              </view>
              <view
                class="radio-item"
                :class="{ active: memberForm.gender === 2 }"
                @click="memberForm.gender = 2"
              >
                <text class="radio-icon">👩</text>
                <text>女</text>
              </view>
            </view>
          </view>

          <view class="form-item">
            <text class="label required">状态</text>
            <view class="radio-group">
              <view
                class="radio-item"
                :class="{ active: memberForm.isAlive }"
                @click="memberForm.isAlive = true"
              >
                <text class="radio-icon">❤️</text>
                <text>在世</text>
              </view>
              <view
                class="radio-item"
                :class="{ active: !memberForm.isAlive }"
                @click="memberForm.isAlive = false"
              >
                <text class="radio-icon">🕯️</text>
                <text>已故</text>
              </view>
            </view>
          </view>

          <!--      <view class="form-item">
            <text class="label required">与申请人关系</text>
            <picker
              :value="relationIndex"
              :range="relationOptions"
              @change="onRelationChange"
            >
              <view class="picker-input">
                <text>{{ relationOptions[relationIndex] }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view> -->

          <!-- <view class="form-item">
            <view class="checkbox-item">
              <checkbox
                :checked="memberForm.isSelf"
                @change="onSelfChange"
              />
              <text class="checkbox-label">设为本人</text>
            </view>
          </view> -->
        </view>

        <view class="popup-footer">
          <button class="btn btn-default" @click="closeMemberPopup">取消</button>
          <button class="btn btn-primary" :disabled="!canSaveMember" @click="saveMember">
            确定
          </button>
        </view>
      </view>
    </view>

    <!-- 确认弹窗 -->
    <view v-if="showConfirmPopup" class="popup-overlay" @click="closeConfirmPopup">
      <view class="popup-container confirm-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">确认提交</text>
        </view>
        <view class="popup-content">
          <text class="confirm-text">确定要提交家谱加入申请吗？</text>
          <text class="confirm-tip">提交后将等待管理员审核，请确保信息准确</text>
        </view>
        <view class="popup-footer">
          <button class="btn btn-default" @click="closeConfirmPopup">取消</button>
          <button class="btn btn-primary" @click="confirmSubmit">确定提交</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import FamilyAPI from "@/api/genealogy/family";
import GenealogyGeneration from "./components/GenealogyGeneration.vue";

export default {
  name: "GenealogyJoin",
  components: { GenealogyGeneration },
  data() {
    return {
      familyId: null,
      joinReasonForm: {
        reason: "",
        familyData: null,
      },
      familyMembers: [], // 保持扁平结构用于内部处理
      familyTree: null, // 新增：嵌套结构用于显示和提交
      memberForm: {
        firstName: "",
        lastName: "",
        gender: 1,
        isAlive: true,
        isSelf: false,
        relation: "父亲",
        parentId: "", // 新增
      },
      editingMember: null,
      relationIndex: 0,
      relationOptions: [
        "父亲",
        "母亲",
        "爷爷",
        "奶奶",
        "外公",
        "外婆",
        "兄弟",
        "姐妹",
        "配偶",
        "儿子",
        "女儿",
        "其他",
      ],
      showMemberPopup: false,
      showConfirmPopup: false,
      isSubmitting: false,
      reasonWarning: false,
      parentIndex: 0, // 新增
      parentOptions: ["无（顶级）"], // 新增
      editingFlag: 0, // 定义弹出框标题显示
      treeScale: 1, // 树型显示缩放比例
      optListFlag: false, // 控制弹出框显示
      currentOperationChild: null, // 当前操作的子成员（用于添加父辈时建立连接）
    };
  },

  computed: {
    canSubmit() {
      return (
        this.joinReasonForm.reason.trim() &&
        this.familyMembers.length > 0 &&
        this.familyMembers.some((member) => member.isSelf)
      );
    },
    canSaveMember() {
      return this.memberForm.firstName && this.memberForm.lastName && this.memberForm.relation;
    },
    rootMembers() {
      return this.familyMembers.filter((m) => !m.parentId);
    },
  },

  watch: {
    familyMembers: {
      handler() {
        // 当扁平数据变化时，重新构建嵌套结构
        this.buildFamilyTree();
        this.$nextTick(() => {
          // Removed G6 rendering logic
        });
      },
      deep: true,
    },
  },

  mounted() {
    this.$nextTick(() => {
      // Removed G6 rendering logic
    });
  },

  onLoad(options) {
    this.familyId = options.familyId;
    this.initDefaultMember();
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 初始化默认成员（本人）
    initDefaultMember() {
      this.familyMembers = [
        {
          id: Date.now().toString(),
          firstName: "",
          lastName: "",
          gender: 1,
          isAlive: true,
          isSelf: true,
          relation: "本人",
          parentId: "",
        },
      ];

      // 构建初始嵌套结构
      this.buildFamilyTree();

      // 添加一些示例数据用于演示
      setTimeout(() => {
        this.addDemoData();
      }, 1000);
    },

    // 添加演示数据
    addDemoData() {
      const selfId = this.familyMembers[0].id;

      // 添加父亲
      const father = {
        id: (Date.now() + 1).toString(),
        firstName: "父亲",
        lastName: "姓氏",
        gender: 1,
        isAlive: true,
        isSelf: false,
        relation: "父亲",
        parentId: "",
      };

      // 添加母亲
      const mother = {
        id: (Date.now() + 2).toString(),
        firstName: "母亲",
        lastName: "姓氏",
        gender: 2,
        isAlive: true,
        isSelf: false,
        relation: "母亲",
        parentId: "",
      };

      // 添加儿子
      const son = {
        id: (Date.now() + 3).toString(),
        firstName: "儿子",
        lastName: "姓氏",
        gender: 1,
        isAlive: true,
        isSelf: false,
        relation: "儿子",
        parentId: selfId,
      };

      // 添加女儿
      const daughter = {
        id: (Date.now() + 4).toString(),
        firstName: "女儿",
        lastName: "姓氏",
        gender: 2,
        isAlive: true,
        isSelf: false,
        relation: "女儿",
        parentId: selfId,
      };

      // 添加爷爷
      const grandfather = {
        id: (Date.now() + 5).toString(),
        firstName: "爷爷",
        lastName: "姓氏",
        gender: 1,
        isAlive: true,
        isSelf: false,
        relation: "爷爷",
        parentId: father.id,
      };

      // this.familyMembers.push(father);
    },

    // 添加家庭成员
    addFamilyMember() {
      this.editingMember = null;
      this.memberForm = {
        firstName: "",
        lastName: "",
        gender: 1,
        isAlive: true,
        isSelf: false,
        relation: "父亲",
        parentId: "",
      };
      // 生成父节点选项
      this.parentOptions = [
        "无（顶级）",
        ...this.familyMembers.map((m) => m.firstName + m.lastName),
      ];
      this.parentIndex = 0;
      this.showMemberPopup = true;
    },

    // 编辑成员
    editMember(member) {
      console.log("编辑成员，传入数据:", member);

      // 隐藏操作列表
      this.optListFlag = false;
      this.showMemberPopup = true;

      // 设置编辑成员
      this.editingMember = member;

      // 设置表单数据
      if (member) {
        // 深拷贝成员数据到表单
        this.memberForm = {
          firstName: member.firstName || "",
          lastName: member.lastName || "",
          gender: member.gender || 1,
          isAlive: member.isAlive !== undefined ? member.isAlive : true,
          isSelf: member.isSelf || false,
          relation: member.relation || "父亲",
          parentId: member.parentId || "",
        };

        console.log("编辑模式，表单数据回显:", this.memberForm);

        // 生成父节点选项
        this.parentOptions = [
          "无（顶级）",
          ...this.familyMembers.map((m) => m.firstName + m.lastName),
        ];
        this.parentIndex = member.parentId
          ? this.familyMembers.findIndex((m) => m.id === member.parentId) + 1
          : 0;
      } else {
        // 新增成员时，重置表单
        this.memberForm = {
          firstName: "",
          lastName: "",
          gender: 1,
          isAlive: true,
          isSelf: false,
          relation: "父亲",
          parentId: "",
        };
        console.log("新增模式，重置表单数据:", this.memberForm);

        this.parentOptions = [
          "无（顶级）",
          ...this.familyMembers.map((m) => m.firstName + m.lastName),
        ];
        this.parentIndex = 0;
      }
    },

    // 删除成员
    removeMember(member) {
      console.log("删除成员:", member);

      // 检查是否可以删除
      if (member.isSelf) {
        uni.showToast({
          title: "不能删除本人信息",
          icon: "none",
        });
        return;
      }

      // 检查是否有子辈
      if (this.hasChildren(member)) {
        uni.showToast({
          title: "该成员有子辈，不能删除",
          icon: "none",
        });
        return;
      }

      // 检查是否是配偶
      const isSpouse =
        member.relation &&
        (member.relation.includes("配偶") ||
          member.relation.includes("妻子") ||
          member.relation.includes("丈夫"));

      if (isSpouse) {
        // 删除配偶：从对应成员的spouseList中删除
        const parentMember = this.familyMembers.find(
          (m) => m.spouseList && m.spouseList.some((spouse) => spouse.id === member.id)
        );

        if (parentMember) {
          const spouseIndex = parentMember.spouseList.findIndex(
            (spouse) => spouse.id === member.id
          );
          if (spouseIndex > -1) {
            parentMember.spouseList.splice(spouseIndex, 1);
            console.log("配偶删除成功，剩余配偶:", parentMember.spouseList);

            uni.showToast({
              title: "配偶删除成功",
              icon: "success",
            });
          }
        }
      } else {
        // 删除主成员：同时删除其配偶列表
        const hasSpouse = member.spouseList && member.spouseList.length > 0;

        let confirmMessage = `确定要删除 ${member.firstName}${member.lastName} 吗？`;
        if (hasSpouse) {
          confirmMessage += `\n注意：该成员有${member.spouseList.length}个配偶，将一并删除`;
        }

        uni.showModal({
          title: "确认删除",
          content: confirmMessage,
          success: (res) => {
            if (res.confirm) {
              const index = this.familyMembers.findIndex((m) => m.id === member.id);
              if (index > -1) {
                this.familyMembers.splice(index, 1);
                console.log("成员删除成功，剩余成员:", this.familyMembers);

                uni.showToast({
                  title: "删除成功",
                  icon: "success",
                });
              }
            }
          },
        });
      }
    },

    // 关系选择变化
    onRelationChange(e) {
      this.relationIndex = e.detail.value;
      this.memberForm.relation = this.relationOptions[this.relationIndex];
    },

    // 本人状态变化
    onSelfChange(e) {
      this.memberForm.isSelf = e.detail.value;

      // 如果设置为本人，取消其他成员的本人状态
      if (this.memberForm.isSelf) {
        this.familyMembers.forEach((member) => {
          member.isSelf = false;
        });
      }
    },

    // 保存成员
    saveMember() {
      // 表单验证
      if (!this.memberForm.firstName || !this.memberForm.lastName) {
        uni.showToast({
          title: "请填写完整姓名",
          icon: "none",
        });
        return;
      }

      // 处理parentId
      if (this.parentIndex === 0) {
        this.memberForm.parentId = "";
      } else {
        this.memberForm.parentId = this.familyMembers[this.parentIndex - 1].id;
      }

      console.log("当前编辑成员:", this.editingMember);
      console.log("当前表单数据:", this.memberForm);
      console.log("当前家庭成员数量:", this.familyMembers.length);

      // 判断逻辑：如果是编辑模式，更新现有成员；否则添加新成员
      if (this.editingMember != null) {
        // 编辑现有成员
        const index = this.familyMembers.findIndex((member) => member.id === this.editingMember.id);
        if (index !== -1) {
          // 保持原有ID，更新其他属性
          this.familyMembers[index] = {
            ...this.familyMembers[index],
            ...this.memberForm,
            id: this.editingMember.id, // 保持原有ID
          };
          console.log("编辑现有成员，更新后:", this.familyMembers[index]);
          uni.showToast({
            title: "成员信息已更新",
            icon: "success",
          });
        }
      } else {
        // 添加新成员
        if (this.editingFlag === 3) {
          // 添加配偶：将配偶数据添加到当前操作成员的spouseList中
          const currentMember = this.familyMembers.find(
            (m) => m.id === this.currentOperationChild?.id
          );
          if (currentMember) {
            // 初始化spouseList数组（如果不存在）
            if (!currentMember.spouseList) {
              currentMember.spouseList = [];
            }

            // 创建配偶数据
            const spouseData = {
              id: Date.now().toString(),
              firstName: this.memberForm.firstName,
              lastName: this.memberForm.lastName,
              gender: this.memberForm.gender,
              isAlive: this.memberForm.isAlive,
              isSelf: false,
              relation: this.memberForm.relation,
              parentId: this.memberForm.parentId,
            };

            // 添加到spouseList
            currentMember.spouseList.push(spouseData);

            console.log("添加配偶到spouseList:", spouseData);
            console.log("更新后的成员:", currentMember);

            uni.showToast({
              title: "已添加配偶",
              icon: "success",
            });
          }
        } else {
          // 添加其他类型成员（父辈、子辈等）
          const newMember = {
            id: Date.now().toString(),
            ...this.memberForm,
          };
          this.familyMembers.push(newMember);
          console.log("添加新成员:", newMember);

          // 如果是添加父辈操作，需要更新子成员的parentId
          if (this.editingFlag === 1 && this.currentOperationChild) {
            const childIndex = this.familyMembers.findIndex(
              (m) => m.id === this.currentOperationChild.id
            );
            if (childIndex !== -1) {
              this.familyMembers[childIndex].parentId = newMember.id;
              console.log("更新子成员parentId:", this.familyMembers[childIndex]);
              console.log("新父辈成员:", newMember);
              console.log("父子关系建立完成");
            }
          }

          // 根据操作类型显示不同的提示
          const actionText =
            this.editingFlag === 1 ? "父辈" : this.editingFlag === 2 ? "子辈" : "成员";
          uni.showToast({
            title: `已添加${actionText}`,
            icon: "success",
          });
        }
      }

      console.log("最终家庭成员:", this.familyMembers);
      this.closeMemberPopup();
    },

    // 关闭成员弹窗
    closeMemberPopup() {
      this.showMemberPopup = false;
      this.editingMember = null;
      this.editingFlag = 0; // 重置编辑标志
      this.currentOperationChild = null; // 重置当前操作的子成员
    },

    // 获取关系文本
    getRelationText(member) {
      if (member.isSelf) return "本人";
      return member.relation;
    },

    // 提交申请
    submitApplication() {
      if (!this.canSubmit) {
        uni.showToast({
          title: "请完善申请信息",
          icon: "none",
        });
        return;
      }

      this.showConfirmPopup = true;
    },
    // 取消订单提交
    closeConfirmPopup() {
      this.showConfirmPopup = false;
    },
    // 确认提交
    confirmSubmit() {
      this.showConfirmPopup = false;
      this.isSubmitting = true;

      // 构建家谱树数据
      const familyData = this.buildFamilyTreeData();

      FamilyAPI.join({
        familyId: this.familyId,
        reason: this.joinReasonForm.reason,
        familyData: familyData,
      })
        .then(() => {
          uni.hideLoading();
          uni.showToast({
            title: "申请提交成功",
            icon: "success",
          });
          // 延迟返回，让用户看到成功提示
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/genealogy/index",
            });
          }, 1000);
        })
        .catch((error) => {
          uni.hideLoading();
          uni.showToast({
            title: "申请提交失败",
            icon: "none",
          });
          console.error("加入家谱失败:", error);
        })
        .finally(() => {
          this.isSubmitting = false;
        });
    },

    // 构建家谱树数据
    buildFamilyTreeData() {
      // 使用嵌套结构
      if (!this.familyTree || this.familyTree.length === 0) {
        return null;
      }

      // 递归处理节点，确保包含spouseList
      const processNode = (node) => {
        if (!node) return null;

        return {
          id: node.id,
          firstName: node.firstName,
          lastName: node.lastName,
          gender: node.gender,
          isAlive: node.isAlive,
          isSelf: node.isSelf,
          spouseList: node.spouseList || [], // 包含配偶列表
          children: node.children ? node.children.map((child) => processNode(child)) : [],
        };
      };

      // 找到本人节点
      const findSelfNode = (nodes) => {
        for (const node of nodes) {
          if (node.isSelf) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const found = findSelfNode(node.children);
            if (found) return found;
          }
        }
        return null;
      };

      const selfNode = findSelfNode(this.familyTree);
      if (!selfNode) {
        console.warn("未找到本人节点");
        return processNode(this.familyTree[0]); // 返回第一个根节点作为备选
      }

      const processedNode = processNode(selfNode);
      console.log("提交的嵌套家谱树数据:", processedNode);
      return processedNode;
    },

    // 构建嵌套的家谱树结构
    buildFamilyTree() {
      if (this.familyMembers.length === 0) {
        this.familyTree = null;
        return;
      }

      // 创建成员映射表
      const memberMap = new Map();
      this.familyMembers.forEach((member) => {
        memberMap.set(member.id, {
          ...member,
          children: [],
          spouseList: member.spouseList || [], // 确保spouseList被复制
        });
      });

      // 构建树结构
      const rootMembers = [];
      this.familyMembers.forEach((member) => {
        const node = memberMap.get(member.id);
        if (member.parentId && memberMap.has(member.parentId)) {
          // 有父节点，添加到父节点的children中
          const parent = memberMap.get(member.parentId);
          parent.children.push(node);
        } else {
          // 没有父节点，是根节点
          rootMembers.push(node);
        }
      });

      this.familyTree = rootMembers;
      console.log("构建的嵌套家谱树:", this.familyTree);
    },

    // 将嵌套结构转换为扁平结构（用于内部处理）
    flattenFamilyTree(tree, parentId = "") {
      const flatMembers = [];

      if (Array.isArray(tree)) {
        tree.forEach((node) => {
          flatMembers.push(...this.flattenFamilyTree(node, parentId));
        });
      } else if (tree) {
        const member = { ...tree };
        member.parentId = parentId;
        delete member.children;
        flatMembers.push(member);

        if (tree.children && tree.children.length > 0) {
          tree.children.forEach((child) => {
            flatMembers.push(...this.flattenFamilyTree(child, tree.id));
          });
        }
      }

      return flatMembers;
    },

    // 处理申请说明输入
    onReasonInput(e) {
      this.joinReasonForm.reason = e.detail.value;
      this.reasonWarning = this.joinReasonForm.reason.length >= 90;
    },

    // 处理姓氏输入
    onFirstNameInput(e) {
      this.memberForm.firstName = e.detail.value;
    },

    // 处理名字输入
    onLastNameInput(e) {
      this.memberForm.lastName = e.detail.value;
    },

    // 选择父节点变化
    onParentChange(e) {
      this.parentIndex = e.detail.value;
      if (this.parentIndex === 0) {
        this.memberForm.parentId = "";
      } else {
        this.memberForm.parentId = this.familyMembers[this.parentIndex - 1].id;
      }
    },

    // 处理节点点击
    handleNodeClick(person) {
      console.log("节点点击，传入数据:", person);
      // 设置当前编辑的成员
      this.editingMember = person;
      // 显示操作弹窗
      this.optListFlag = true;
    },

    // 处理树操作
    handleTreeAction(data) {
      const { action, person } = data;
      console.log("处理树操作:", action, person);

      switch (action) {
        case "edit":
          console.log("执行编辑操作，成员数据:", person);
          this.editingFlag = 0;
          this.editMember(person);
          break;
        case "add-parent":
          this.editingFlag = 1;
          this.addParentMember(person);
          break;
        case "add-child":
          this.editingFlag = 2;
          this.addChildMember(person);
          break;
        case "add-spouse":
          this.editingFlag = 3;
          this.addSpouseMember(person);
          break;
        case "delete":
          this.removeMember(person);
          break;
      }
    },

    // 添加父辈成员
    addParentMember(childMember) {
      console.log("添加父辈成员，子成员:", childMember);
      this.showMemberPopup = true;
      this.editingMember = null; // 新增成员，不是编辑
      this.currentOperationChild = childMember; // 记住当前操作的子成员
      // 根据子成员的性别智能设置父辈的性别和关系
      const isMaleChild = childMember.gender === 1;
      const relation = isMaleChild ? "父亲" : "母亲";
      const gender = isMaleChild ? 1 : 2;
      this.memberForm = {
        firstName: childMember.firstName || "",
        lastName: "", // 只保留姓氏
        gender: gender,
        isAlive: true,
        isSelf: false,
        relation: relation,
        parentId: "", // 父辈通常是顶级成员
      };
      this.parentOptions = [
        "无（顶级）",
        ...this.familyMembers.map((m) => m.firstName + m.lastName),
      ];
      this.parentIndex = 0;
      console.log("父辈表单初始化:", this.memberForm);
    },

    // 添加子辈成员
    addChildMember(parentMember) {
      console.log("添加子辈成员，父成员:", parentMember);
      // 重置表单数据
      this.memberForm = {
        firstName: parentMember.firstName || "",
        lastName: "", // 只保留父辈的姓氏
        gender: 1, // 默认男性，用户可修改
        isAlive: true,
        isSelf: false,
        relation: "儿子", // 默认儿子，用户可修改
        parentId: parentMember.id,
      };
      this.showMemberPopup = true;
      this.editingMember = null; // 新增成员，不是编辑
      this.parentOptions = [
        "无（顶级）",
        ...this.familyMembers.map((m) => m.firstName + m.lastName),
      ];
      this.parentIndex = this.familyMembers.findIndex((m) => m.id === parentMember.id) + 1;
      console.log("子辈表单初始化:", this.memberForm);
    },

    // 添加配偶成员
    addSpouseMember(member) {
      console.log("添加配偶成员，原成员:", member);
      this.showMemberPopup = true;
      this.editingMember = null; // 新增成员，不是编辑
      this.currentOperationChild = member; // 记住当前操作的成员
      // 智能设置配偶信息
      const spouseGender = member.gender === 1 ? 2 : 1; // 相反性别
      const spouseRelation = member.gender === 1 ? "妻子" : "丈夫";
      this.memberForm = {
        firstName: "",
        lastName: "", // 配偶不保留姓氏
        gender: spouseGender,
        isAlive: true,
        isSelf: false,
        relation: spouseRelation,
        parentId: member.parentId || "", // 配偶通常有相同的父辈
      };
      this.parentOptions = [
        "无（顶级）",
        ...this.familyMembers.map((m) => m.firstName + m.lastName),
      ];
      this.parentIndex = member.parentId
        ? this.familyMembers.findIndex((m) => m.id === member.parentId) + 1
        : 0;
      console.log("配偶表单初始化:", this.memberForm);
    },

    // 计算成员X坐标
    getMemberX(member, index) {
      const baseX = 200; // 基础位置
      const spacing = 250; // 成员间距
      return baseX + index * spacing;
    },

    // 计算成员Y坐标
    getMemberY(member) {
      return 100; // 固定Y坐标
    },

    // 检查成员是否有子辈
    hasChildren(member) {
      return this.familyMembers.some((m) => m.parentId === member.id);
    },

    // 检查是否是配偶
    isSpouse(member) {
      return (
        member &&
        member.relation &&
        (member.relation.includes("配偶") ||
          member.relation.includes("妻子") ||
          member.relation.includes("丈夫"))
      );
    },

    // 检查节点是否有数据（不是初始状态）
    hasNodeData(member) {
      if (!member) return false;
      // 检查是否有姓名数据
      return !!(
        member.firstName &&
        member.firstName.trim() &&
        member.lastName &&
        member.lastName.trim()
      );
    },

    // 缩放控制
    zoomIn() {
      this.treeScale = Math.min(2, this.treeScale * 1.1);
    },
    zoomOut() {
      this.treeScale = Math.max(0.5, this.treeScale * 0.9);
    },
    resetZoom() {
      this.treeScale = 1;
    },

    // Removed G6 rendering logic
  },
};
</script>

<style scoped>
.opt-popup-overlay {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.35);
  z-index: 11000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.opt-popup-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 18rpx 32rpx 0 32rpx;
  gap: 18rpx;
}

.opt-action-item {
  width: 80%;
  min-width: 200rpx;
  max-width: 350rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  font-size: 30rpx;
  color: #fff;
  background-color: #409eff;
  padding: 22rpx 0;
  border-radius: 8rpx;
  border: none;
  margin: 0 auto;
  cursor: pointer;
  transition:
    background 0.2s,
    color 0.2s;
  box-shadow: 0 2rpx 8rpx rgba(64, 158, 255, 0.08);
}

.action-icon {
  font-size: 32rpx;
}

.action-text {
  font-size: 30rpx;
}

.opt-action-item:last-child {
  border-bottom: none;
}

.opt-action-item.delete {
  background-color: #f56c6c;
  color: #fff;
}

.opt-action-item:active {
  background-color: #337ecc;
}

.opt-action-item.delete:active {
  background-color: #d93026;
}

.opt-popup-container {
  background: #fff;
  border-radius: 18rpx;
  min-width: 480rpx;
  max-width: 90vw;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.18);
  padding: 0 0 30rpx 0;
  animation: popup-fade-in 0.2s;
}

.opt-popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 32rpx 18rpx 32rpx;
  border-bottom: 1rpx solid #eee;
}

.opt-popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.opt-popup-close {
  font-size: 40rpx;
  color: #bbb;
  cursor: pointer;
  transition: color 0.2s;
}

.opt-popup-close:active {
  color: #888;
}

.opt-popup-actions {
  display: flex;
  flex-direction: column;
  padding: 18rpx 32rpx 0 32rpx;
  gap: 18rpx;
}

@keyframes popup-fade-in {
  from {
    transform: scale(0.95);
    opacity: 0;
  }

  to {
    transform: scale(1);
    opacity: 1;
  }
}

.join-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 2rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 1000000;
  background: #fff;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.back-icon {
  font-size: 32rpx;
  color: #333;
}

.back-text {
  font-size: 28rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.header-right {
  width: 80rpx;
}

.form-container {
  padding: 30rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.section-subtitle {
  font-size: 24rpx;
  color: #999;
  font-weight: normal;
}

.form-item {
  margin-bottom: 30rpx;
  position: relative;
  z-index: 10002;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.label.required {
  color: #f00;
}

.textarea {
  width: 100%;
  padding: 20rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  min-height: 120rpx;
  box-sizing: border-box;
}

.char-count {
  position: absolute;
  bottom: 10rpx;
  right: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.char-count.warning {
  color: #f00;
}

.family-tree-container {
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  overflow: hidden;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-bottom: 2rpx solid #eee;
}

.tree-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.btn-sm {
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}

.btn-icon {
  font-size: 24rpx;
  margin-right: 5rpx;
}

.tree-content {
  padding: 20rpx;
  min-height: 400rpx;
}

.tree-scroll-container {
  width: 100%;
  height: 800rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  background: #fafbfc;
  overflow: hidden;
}

.tree-canvas {
  position: relative;
  width: 4000rpx;
  height: 3000rpx;
  padding: 100rpx;
  transform-origin: 0 0;
  transition: transform 0.3s ease;
}

.zoom-controls {
  display: flex;
  justify-content: center;
  gap: 20rpx;
  margin-top: 20rpx;
}

.zoom-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #fff;
  border: 1rpx solid #ddd;
  font-size: 24rpx;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  padding: 0;
}

.zoom-btn::after {
  border: none;
}

.zoom-btn:hover {
  background: #f0f0f0;
  border-color: #409eff;
  color: #409eff;
}

.empty-state {
  text-align: center;
  padding: 50rpx 0;
  color: #999;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.empty-tip {
  font-size: 24rpx;
}

.member-card {
  background-color: #fff;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 15rpx;
}

.member-card.is-self {
  border-color: #409eff;
  background-color: #f0f8ff;
}

.member-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15rpx;
}

.member-info {
  flex: 1;
}

.member-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.member-tags {
  display: flex;
  gap: 10rpx;
  flex-wrap: wrap;
}

.tag {
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
}

.tag.male {
  background-color: #e3f2fd;
  color: #1976d2;
}

.tag.female {
  background-color: #fce4ec;
  color: #c2185b;
}

.tag.alive {
  background-color: #e8f5e8;
  color: #2e7d32;
}

.tag.deceased {
  background-color: #f5f5f5;
  color: #666;
}

.tag.self {
  background-color: #fff3e0;
  color: #f57c00;
}

.member-actions {
  display: flex;
  gap: 10rpx;
}

.btn-icon {
  background: none;
  border: none;
  font-size: 28rpx;
  padding: 5rpx;
}

.member-relation {
  padding-top: 10rpx;
  border-top: 1rpx solid #eee;
}

.relation-text {
  font-size: 26rpx;
  color: #666;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 20rpx;
  background-color: #fff3cd;
  border-radius: 8rpx;
  margin-top: 20rpx;
}

.tip-icon {
  font-size: 28rpx;
}

.tip-text {
  font-size: 26rpx;
  color: #856404;
}

.tree-tips {
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-top: 20rpx;
  border-left: 4rpx solid #409eff;
}

.tip-title {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.tip-item {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
  line-height: 1.4;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 2rpx solid #eee;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.btn {
  flex: 1;
  padding: 20rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
  text-align: center;
  line-height: 22px;
}

.btn-primary {
  background-color: #409eff;
  color: #fff;
}

.btn-default {
  background-color: #fff;
  color: #333;
  border: 2rpx solid #ddd;
}

.btn:disabled {
  opacity: 0.5;
  pointer-events: none;
}

.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-container {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.18);
  background: #fff;
  padding: 0 0.5rem;
  overflow: hidden;
}

.confirm-popup {
  width: 500rpx;
  max-height: 60vh;
}

.popup-header {
  padding: 28px 32px 16px 32px;
  border-bottom: 1px solid #f0f0f0;
  text-align: center;
}

.popup-title {
  font-size: 22px;
  font-weight: 700;
  color: #222;
  letter-spacing: 1px;
}

.popup-close {
  position: absolute;
  right: 24px;
  top: 24px;
  font-size: 28px;
  color: #bbb;
  cursor: pointer;
}

.popup-content {
  padding: 10px 32px 10px 10px;
}

.form-item {
  margin-bottom: 22px;
}

.input {
  width: 100%;
  height: 44px;
  border: 1.5px solid #e0e0e0;
  border-radius: 8px;
  padding: 0 14px;
  font-size: 16px;
  background: #fafbfc;
  transition: border-color 0.2s;
}

.input:focus {
  border-color: #409eff;
  background: #fff;
  outline: none;
}

.input::placeholder {
  color: #bbb;
}

.radio-group {
  display: flex;
  gap: 16px;
}

.radio-item {
  flex: 1;
  padding: 10px 0;
  border-radius: 8px;
  border: 1.5px solid #e0e0e0;
  background: #fafbfc;
  text-align: center;
  cursor: pointer;
  transition:
    border-color 0.2s,
    background 0.2s;
}

.radio-item.active {
  border-color: #409eff;
  background: #eaf4ff;
  color: #409eff;
}

.radio-item:hover {
  background: #f0f7ff;
}

.picker-input {
  border-radius: 8px;
  border: 1.5px solid #e0e0e0;
  background: #fafbfc;
  height: 44px;
  display: flex;
  align-items: center;
  padding: 0 14px;
  font-size: 16px;
  cursor: pointer;
}

.checkbox-item {
  margin-top: 6px;
}

.popup-footer {
  display: flex;
  gap: 18px;
  padding: 24px 32px 28px 32px;
  border-top: 1px solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 44px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
  border: none;
  transition: background 0.2s;
}

.btn-primary {
  background: #409eff;
  color: #fff;
}

.btn-primary:hover {
  background: #3076d6;
}

.btn-default {
  background: #f5f5f5;
  color: #333;
  border: 1.5px solid #e0e0e0;
}

.btn-default:hover {
  background: #eaeaea;
}

.family-tree-visual {
  padding: 16px 0 0 16px;
}

.tree-node {
  margin-left: 20px;
  border-left: 1px dashed #ccc;
  padding-left: 10px;
}

.node-content {
  margin-bottom: 4px;
}

.node-name {
  font-weight: bold;
  color: #409eff;
}

.node-tag {
  margin-left: 8px;
  color: #999;
  font-size: 12px;
}

.node-children {
  margin-top: 2px;
}
</style>
